package com.jinly.ryder.account.web.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jinly.ryder.account.config.AuthProperties;
import com.jinly.ryder.common.auth.model.TokenInfo;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Optional;


public class TokenUtil {
    public static Optional<TokenInfo> parseToken(HttpServletRequest request, AuthProperties authProperties) {
        String token = request.getHeader("x-token");
        if (token != null) {
            try {
                JWTVerifier verifier = JWT.require(Algorithm.HMAC256(authProperties.getSecret())).withIssuer(authProperties.getIssuer()).build();
                DecodedJWT decodedJWT = verifier.verify(token);
                TokenInfo tokenInfo = new TokenInfo(decodedJWT.getClaim("uid").asLong(), decodedJWT.getClaim("sid").asString());
                return Optional.ofNullable(tokenInfo);
            } catch (Exception e) {

            }
        }
        return Optional.empty();
    }

    public static String getToken(AuthProperties authProperties, TokenInfo tokenInfo) {
        return JWT.create().withIssuer(authProperties.getIssuer()).withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * authProperties.getExpireMinutes()))
                .withClaim("uid", tokenInfo.getUserId())
                .withClaim("sid", tokenInfo.getSessionId())
                .sign(Algorithm.HMAC256(authProperties.getSecret()));
    }

}
